package com.atguigu.util

import java.sql.{Connection, PreparedStatement, ResultSet, SQLException}
import java.util.Properties

import com.alibaba.druid.pool.DruidDataSourceFactory
import javax.sql.DataSource

/**
 * description ：druid 连接工具类
 * author      ：剧情再美终是戏 
 * mail        : 13286520398@163.com
 * date        ：Created in 2020/3/11 15:24
 * modified By ：
 * version:    : 1.0
 */
object DataSourceUtil extends Serializable {

  // 获取连接池
  val props = new Properties
  private var dataSource: DataSource = null
  props.setProperty("url", ConfigManager.getProperty("jdbc.url"))
  props.setProperty("username", ConfigManager.getProperty("jdbc.user"))
  props.setProperty("password", ConfigManager.getProperty("jdbc.password"))
  props.setProperty("initialSize", "5") //初始化大小
  props.setProperty("maxActive", "10") //最大连接
  props.setProperty("minIdle", "5") //最小连接
  props.setProperty("maxWait", "60000") //等待时长
  props.setProperty("timeBetweenEvictionRunsMillis", "2000") //配置多久进行一次检测,检测需要关闭的连接 单位毫秒
  props.setProperty("minEvictableIdleTimeMillis", "600000") //配置连接在连接池中最小生存时间 单位毫秒
  props.setProperty("maxEvictableIdleTimeMillis", "900000") //配置连接在连接池中最大生存时间 单位毫秒
  props.setProperty("validationQuery", "select 1")
  props.setProperty("testWhileIdle", "true")
  props.setProperty("testOnBorrow", "false")
  props.setProperty("testOnReturn", "false")
  props.setProperty("keepAlive", "true")
  props.setProperty("phyMaxUseCount", "100000")
  dataSource = DruidDataSourceFactory.createDataSource(props)

  /**
   * 通过 druid 连接池获取 mysql 连接
   *
   * @Author 剧情再美终是戏
   * @Date 2020/3/11 15:29
   * @param
   * @return java.sql.Connection
   * @Version 1.0
   **/
  def getConnection(): Connection = {
    dataSource match {
      case null => null
      case _ => dataSource.getConnection
    }
  }


  /**
   * 关闭 druid 连接资源，包含关闭清除结果集， 关闭 sql stmt， 关闭连接
   *
   * @Author 剧情再美终是戏
   * @Date 2020/3/11 15:33
   * @param resultSet         结果集
   * @param preparedStatement ssql stmt
   * @param connection        连接
   * @return void
   * @Version 1.0
   **/
  def closeResource(resultSet: ResultSet, preparedStatement: PreparedStatement,
                    connection: Connection): Unit = {
    // 关闭结果集
    // ctrl+alt+m 将java语句抽取成方法
    closeResultSet(resultSet)
    // 关闭语句执行者
    closePrepareStatement(preparedStatement)
    // 关闭连接
    closeConnection(connection)
  }

  private def closeConnection(connection: Connection) = {
    if (connection != null) try connection.close()
    catch {
      case e: SQLException =>
        e.printStackTrace()
    }
  }

  private def closePrepareStatement(preparedStatement: PreparedStatement) = {
    if (preparedStatement != null) try preparedStatement.close()
    catch {
      case e: SQLException =>
        e.printStackTrace()
    }
  }


  private def closeResultSet(resultSet: ResultSet) = {
    if (resultSet != null) try resultSet.close()
    catch {
      case e: SQLException =>
        e.printStackTrace()
    }
  }

}
